(function() {
    z.color_table = function (opts) {
        this.wrap = document.body;
        if (opts) {
            if (opts.wrap) {
                this.wrap = opts.wrap;
            }
        }
        var othis = this;
        
        var table = document.createElement('table');
        this.wrap.appendChild(table);
        table.className = 'color_table';
        table.setAttribute('cellspacing', '0');
        table.setAttribute('cellpadding', '0');
        //table.cellspacing="0";
        //table.cellpadding="0";
        
        var row = null;
        for (var i=0; i < 64; i++) {
            if (i%8 == 0) {
                row = table.insertRow(-1);
            }
            var cell = row.insertCell(-1);
            var r = (i % 4) * 85;
            var g = (Math.floor(i / 4) % 4) * 85;
            var b = (Math.floor(i / 16) % 4) * 85;
            var s = 'rgb(' + r + ', ' + g + ', '+ b + ')';
            cell.setAttribute('style', 'background-color:' + s);
            cell.width = "16px";
            cell.height = "16px";
            cell.rgb = {r:r, g:g, b:b, s:s};
            cell.onmousedown = function (e) {
                if (othis.selected_cell) {
                    othis.selected_cell.innerHTML = '';
                }
                othis.selected_cell = this;
                if ( ! this.style.color) {
                    var rgb = this.rgb;
                    var r = 255 - rgb.r;
                    var g = 255 - rgb.g;
                    var b = 255 - rgb.b;
                    this.style.color = 'rgb(' + r + ', ' + g + ', '+ b + ')';
                }
                
                this.innerHTML = "a";
                othis.select_color(this.rgb);
                return z.cancelEvent(e);
            };
        }
    };
    z.color_table.prototype = {
        select_color: function (rgb) {
            if (this.on_select_color) {
                this.on_select_color(rgb);
            } else {
                alert(rgb.r + ':' + rgb.g + ':' + rgb.b);
            }
        }
    };
})();